package cn.home.bootstrap.publishsubscribe.direct;

import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 接收端和场景3的区别：
 * 在绑定queue和exchange的时候使用了routing key，即从该exchange上只接收routing key指定的消息。
 */
@Slf4j
public class ReceiveLogsDirect {
  private final static String IP = "127.0.0.1";
  private final static int  PORT = 5672;
  private static final String EXCHANGE_NAME = "direct_logs";

  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(IP);
    factory.setPort(PORT);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    //配置交换器，为direct模式
    channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
    String queueName = channel.queueDeclare().getQueue();
    List<String> routeKeys = Arrays.asList("info","debug");
    for(String routeKey : routeKeys){
      channel.queueBind(queueName, EXCHANGE_NAME, routeKey);
    }
    Consumer consumer = new DefaultConsumer(channel) {
      @Override
      public void handleDelivery(String consumerTag, Envelope envelope,
                                 AMQP.BasicProperties properties, byte[] body) throws IOException {
        String message = new String(body, "UTF-8");
        log.info(" [x] Received routeKey :{},message:{} ",envelope.getRoutingKey(),message);
      }
    };
    //自动ack
    channel.basicConsume(queueName, true, consumer);
  }
}

